




//https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=/product/1185794392/?layout_container=pdpPage2column&layout_page_index=2
function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return r[2];
    };
    return 0;
 }



console.log(" get ozon detail ok ");

var auto_get = (getQueryString("auto_get"))
console.log(auto_get);
chrome.runtime.onMessage.addListener(async (msg, sender) => {
  console.log(" get ozon detail msg ok ")
  console.log(msg)
  var sku = msg['data']['sku_id'];
  var type_id = msg['data']['type_id'];
  if(!sku){
        console.log("no sku!! no data!!")
        return;
  }

  var url = 'https://www.ozon.ru/api/entrypoint-api.bx/page/json/v2?url=/product/'+sku+'/?layout_container=pdpPage2column&layout_page_index=2';

  $.ajax({
    url: url,
　　　　 type: 'GET',
    xhrFields: {
        withCredentials: true // 这里设置了withCredentials
    },
    success: function(data) {
       console.log(data);
       var dataItem = {}
       dataItem.type_id = type_id;
       var widgetStates = data['widgetStates'];
       for (const key in widgetStates) {
          if(key.includes("webCurrentSeller")){
                dataItem.this_seller = widgetStates[key];
          }else if(key.includes("webCharacteristics")){
                var webCharacteristicsData = JSON.parse(widgetStates[key]);
                dataItem.title = webCharacteristicsData.productTitle;
                dataItem.attrs = widgetStates[key];
          }
        }
       if(data && data['seo'] && data['seo']['meta']){
            for (const key in data['seo']['meta']) {
                var metaMap = data['seo']['meta'][key];
                if(metaMap['property']=='og:image'){
                    dataItem.pic = metaMap['content'];
                }
           }
       }

       console.log(dataItem);
       var type="ozontemplate";
       var body = dataItem;
       chrome.runtime.sendMessage({ data: {type , body ,sku}, close: false });

    },
    error: function(xhr, status, error) {

        if (xhr.status === 403 && status === "error") {
            var type="ozonapi403";
            chrome.runtime.sendMessage({ data: {type}, close: false });
            console.log("遇到了403错误");
            //中断
        }else{
            location.reload();
        }

    }
});

})

